package com.mtw.bbs.common.redisBase.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;


/**
 * 自定义缓存管理
 * 用于设置缓存过期时间
 */
public class CustomRedisCacheManager extends RedisCacheManager {


    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] array = StringUtils.split(name, "#");
        name = array[0];
        if (array.length > 1) {
            // 解析TTL
            long ttl = Long.parseLong(array[1]);
            // 单位 秒
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));

        }
        return super.createRedisCache(name, cacheConfig);
    }

}
